﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using OnlineVideos.Data;
using OnlineVideos.View_Models;
using Common.Library;
using System.ComponentModel;
using Microsoft.Phone.Shell;
using Common.Utilities;
using System.Threading;
using Microsoft.Phone.Controls;
using Microsoft.Phone.BackgroundAudio;

namespace OnlineVideos
{
    public partial class DownloadedAudios : UserControl
    {
        #region GlobalDeclaration

        List<ShowLinks> objAudioList;
        PersonGalleryPopup galleryPopup = null;
        private bool IsDataLoaded;
        ShowDetail detailModel;
        bool ringtoneimageclicked = false;

        #endregion

        public DownloadedAudios()
        {
            InitializeComponent();
            objAudioList = new List<ShowLinks>();
            IsDataLoaded = false;
        }

        private void lbxAudioList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxAudioList.SelectedIndex == -1)
                return;
            if (ringtoneimageclicked == true)
            {
                lbxAudioList.SelectedIndex = -1;
                return;
            }


            performanceProgressBar.IsIndeterminate = true;
            string showid = (lbxAudioList.SelectedItem as ShowLinks).ShowID.ToString();

            LoadDownLoads(lbxAudioList.SelectedItem as ShowLinks);
            AppSettings.SongID = (lbxAudioList.SelectedItem as ShowLinks).LinkID.ToString();
            AppSettings.AudioImage = (lbxAudioList.SelectedItem as ShowLinks).Songplay;
            Thread AudioThread = new Thread(() =>
            {
                objAudioList = OnlineShow.GetShowLinksByType(showid, LinkType.Audio/*, false*/);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    lbxAudioList.ItemsSource = objAudioList;
                });

            });
            AudioThread.Start();
            lbxAudioList.SelectedIndex = -1;
            performanceProgressBar.IsIndeterminate = false;

        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsDataLoaded == false)
            {
                GetPageDataInBackground();
                detailModel = new ShowDetail();
                IsDataLoaded = true;

            }
            ringtoneimageclicked = false;
        }
        private void GetPageDataInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();

            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            a.Result = OnlineShow.GetShowLinksByType(AppSettings.ShowID, LinkType.Audio/*, false*/);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {

                                            objAudioList = (List<ShowLinks>)a.Result;
                                            if (objAudioList.Count > 0)
                                            {
                                                lbxAudioList.ItemsSource = objAudioList;
                                                tblkFavNoAudio.Visibility = Visibility.Collapsed;

                                                lbxAudioList.Loaded += new RoutedEventHandler(lbxAudioList_Loaded);
                                            }
                                            else
                                            {
                                                tblkFavNoAudio.Text = "No " + AppResources.ShowFavoriteAudioPivotTitle + " available";
                                                tblkFavNoAudio.Visibility = Visibility.Visible;
                                            }
                                        }
                                      );

            bwHelper.RunBackgroundWorkers();
        }
        void lbxAudioList_Loaded(object sender, RoutedEventArgs e)
        {

            if (PhoneApplicationService.Current.State.Keys.Contains("searchtitle"))
            {
                PageHelper.SetSelectedItemForegroundColor(this.lbxAudioList, AppState.searchtitle);
            }
            else
            {
                PageHelper.SetSelectedItemForegroundColor(this.lbxAudioList, "");
            }


        }

        public void LoadDownLoads(ShowLinks linkinfo)
        {

            if (linkinfo.Songplay == Constants.PlayImagePath)
            {
                IEnumerable<DependencyObject> cboxes = PageHelper.GetChildsRecursive(lbxAudioList);

                foreach (DependencyObject obj in cboxes.OfType<PerformanceProgressBar>())
                {
                    Type type = obj.GetType();
                    if (type.Name == "PerformanceProgressBar")
                    {
                        PerformanceProgressBar cb = obj as PerformanceProgressBar;
                        if (cb.Tag.ToString() == linkinfo.LinkUrl)
                        {

                            cb.IsIndeterminate = true;
                        }
                    }
                }

                BackgroundAudioPlayer.Instance.Stop();
                AudioTrack audioTrack = new AudioTrack();
                audioTrack.BeginEdit();
                audioTrack.Source = new Uri(linkinfo.LinkUrl, UriKind.RelativeOrAbsolute);
                audioTrack.Title = linkinfo.Title;
                audioTrack.EndEdit();
                BackgroundAudioPlayer.Instance.Track = audioTrack;
                BackgroundAudioPlayer.Instance.Play();
                BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
                AppSettings.AudioShowID = AppSettings.ShowID;

            }
            else
            {
                BackgroundAudioPlayer.Instance.Pause();
                AppSettings.SongPlayImage = string.Empty;

            }

        }

        void Instance_PlayStateChanged(object sender, EventArgs e)
        {
            PlayState playState = BackgroundAudioPlayer.Instance.PlayerState;
            switch (playState)
            {
                case PlayState.Paused:
                    IEnumerable<DependencyObject> cboxes = PageHelper.GetChildsRecursive(lbxAudioList);

                    foreach (DependencyObject obj in cboxes.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                            {

                                cb.IsIndeterminate = false;
                            }
                        }
                    }

                    break;

                case PlayState.Playing:

                    IEnumerable<DependencyObject> cboxes1 = PageHelper.GetChildsRecursive(lbxAudioList);

                    foreach (DependencyObject obj in cboxes1.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                            {

                                cb.IsIndeterminate = false;
                            }
                        }
                    }

                    break;

            }

        }

        private void ringtone_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

        private void delete_Click(object sender, RoutedEventArgs e)
        {
            ShowDetail detailModel = new ShowDetail();
            detailModel.DeleteDownloadedShowlinks(lbxAudioList, sender as MenuItem,LinkType.Audio);
            GetPageDataInBackground();
        }
    }
}
